package com.common.frame.lifecycle

import android.app.Activity
import android.app.Application
import androidx.annotation.Keep
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import kotlin.system.exitProcess

@Keep
object ActivityManager {

    var callbacks: ActivityLifecycleCallbacks = ActivityLifecycleCallbacks()

    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(callbacks)
    }

    fun observeForever(observer: Observer<ActivityStateType>) {
        ActivityStateLiveData.observeForever(observer)
    }

    fun observe(owner: LifecycleOwner, observer: Observer<ActivityStateType>) {
        ActivityStateLiveData.observe(owner, observer)
    }

    /**
     * 移除监控
     * @param observer Observer<ActivityStateType>
     */
    fun removeObserver(observer: Observer<ActivityStateType>) {
        ActivityStateLiveData.removeObserver(observer)
    }
    fun removeObserver(owner: LifecycleOwner) {
        ActivityStateLiveData.removeObservers(owner)
    }
    /**
     * 获取倒数第二个activity
     */
    fun getLastTwo(): Activity? {
        return callbacks.getLastTwo()
    }

    /**
     * 获取当前的Activity
     *
     * @return
     */
    fun getCurrentActivity(): Activity? {
        return callbacks.getCurrentActivity()
    }

    fun getActivity(cls: Class<*>): Activity? {
        return callbacks.getActivity(cls)
    }

    fun getActivity(simpleName: String): Activity? {
        return callbacks.getActivity(simpleName)
    }

    /**
     * 是否存在
     */
    fun hasActivity(cls: Class<*>): Boolean {
        return callbacks.hasActivity(cls)
    }

    /**
     * 关闭所有页面
     */
    fun finishAllActivity() {
        callbacks.finishAllActivity()
    }

    /**
     * 保留指定页面，关闭其他页面
     *
     * @param activityName
     */
    fun finishActivityExcept(activityName: String) {
        callbacks.finishOtherActivity(activityName)
    }

    /**
     * 保留最后一个，关闭其他页面
     */
    fun finishOtherActivity() {
        callbacks.finishOtherActivity()
    }

    /**
     * 保留指定页面，关闭其他页面
     */
    fun finishOtherActivity(activity: Activity) {
        callbacks.finishOtherActivity(activity)
    }

    fun finishActivity(activityName: String) {
        callbacks.finishActivity(activityName)
    }

    /**
     * 应用是否在后台
     *
     * @return
     */
    fun isApplicationInForeground(): Boolean {
        return callbacks.isAppInForeground()
    }

    fun isInActivityStack(activityName: String):Boolean{
        return callbacks.isInActivityStack(activityName)
    }

    /**
     * 最后一个关闭页面的名称
     */
    fun lastFinishActivityName():String?{
        return callbacks.lastFinishActivityName()
    }

    /**
     * 退出应用
     */
    fun exitApp() {
        callbacks.finishAllActivity()
        exitProcess(0)
    }
}